/**
 * @ngdoc module
 * @name docs.services
 * @description
 *   公文模块相关服务
 */
angular.module('docs.services', [])

/**
 * @ngdoc service
 * @name Docs
 * @module docs.services
 * @description
 *   公文模块数据交互及处理
 */
.factory('Docs', function($http, $ionicLoading, Settings){

  var getModuleUrl = function () {
    return Settings.rootUrl + '/docs';
  }

  return {

    get: function(id) {
      $ionicLoading.show();

      return $http.get(getModuleUrl() + '/show', {
        params: { id: id }
      })
      .success($ionicLoading.hide)
      .error($ionicLoading.hide)
    },

    sign: function(id) {
      return $http.get(getModuleUrl() + '/sign', {
        params: { docid: id }
      })
    }

  }

})

.factory('DocsList', function($http, $ionicLoading, Settings, Utils ) {
  function DocsList(url, options){
    this.url = url;
    this.options = options;

    this.hasMore = true;
    this.docs = [];

    this.params = {};
  }

  angular.extend(DocsList.prototype, {
    getUrl: function() {
      return Settings.rootUrl + this.url;
    },
    /**
     * @ngdoc method
     * @name Docs#fetch
     * @description 
     *   获取文件列表数据
     *   返回数据格式为
     *   {
     *     datas: [
     *       { addtime, author, uid, subject, content, uptime, readstatus... }
     *       ...
     *     ],
     *     pages: { page, pageCount, pageSize }
     *   }
     *   addtime: "1409381646"
     * @param {Obejct} param 查询条件 catid | page | keyword...
     * @returns {Object} promise
     */

    fetch: function(params, reset, extend) {
      var _this = this;
      if(reset) {
        this.docs = [];
        this.hasMore = true;
      }

      if(extend === false) {
        this.params = params;
      } else {
        angular.extend(this.params, params);
      }

      $ionicLoading.show();

      return $http.get(this.getUrl(), {
        params: this.params
      })

      .success(function(res){
        if(res.pages.page < res.pages.pageCount) {
          _this.docs = _this.docs.concat(res.datas);
          // _this.params.page += 1;
        }

        // 判断是否还能加载更多
        _this.hasMore = res.pages.page < res.pages.pageCount - 1
      })
      .success($ionicLoading.hide)
      .error($ionicLoading.hide)
    },

    search: function(keyword) {
      return this.fetch({
        page: 1,
        search: keyword
      }, true);
    },

    loadMore: function() {
      return this.fetch({
        page: this.params.page + 1
      });
    },

    hasDocs: function() {
      return !!this.docs.length;
    }
  });

  return DocsList;
})

.factory('DocsPublished', function(DocsList, Settings) {
  var list = new DocsList('/docs');

  return list;
})

.factory('DocsUnsigned', function(DocsList, Settings) {
  var list = new DocsList('/docs&type=nosign');

  return list;
})

.factory('DocsSigned', function(DocsList, Settings) {
  var list = new DocsList('/docs&type=sign');

  return list;
})


